import os
import logging
from logging.handlers import TimedRotatingFileHandler
import datetime
logger = None
def setup_logger(log_dir):
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    # 创建一个处理器，每天创建一个新的日志文件
    log_file = os.path.join(log_dir, "mylog")
    # 由于TimeRotatingFileHandler自动在文件名加时间戳，这个暂时没办法关闭
    handler = TimedRotatingFileHandler(log_file, when="MIDNIGHT", interval=1, backupCount=7)

    # 定义日志格式
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)

    # 将处理器添加到日志记录器
    logger.addHandler(handler)

    return logger

current_script_dir = os.path.dirname(os.path.abspath(__file__))
# os.chdir(current_script_dir)
logger = setup_logger(os.path.join(current_script_dir,"../../log"))
if __name__ == "__main__":
    log_dir = "/path/to/log/directory"
    logger = setup_logger(log_dir)

    # 示例：记录日志
    logger.debug("This is a debug message.")
    logger.info("This is an info message.")
    logger.warning("This is a warning message.")
    logger.error("This is an error message.")
    logger.critical("This is a critical message.")
